<?php
/**
 * csv文件的操作方法
 * 该代码为重写fgetcsv()函数，
 *  作用：fgetcsv() 函数从打开的文件中解析一行，校验 CSV 字段
 *       fgetcsv() 函数会在到达指定长度或读到文件末尾（EOF）时（以先到者为准），停止返回一个新行。
 *       该函数如果成功则以数组形式返回 CSV 字段，如果失败或者到达文件末尾（EOF）则返回 FALSE。
 *  语法：fgetcsv(file,length,separator,enclosure) 除了file其他都是可选的
 * author: micai
 * date: 2018-11-20
 */

function __fgetcsv(&$handle, $length = NULL, $d = ",", $e = "\"")
{
    $d = preg_quote($d);
    $e = preg_quote($e);
    $_line = "";
    $eof = false;

    while ($eof != true) {
        $_line .= (empty($length) ? fgets($handle) : fgets($handle, $length));
        $itemcnt = preg_match_all("/" . $e . "/", $_line, $dummy);

        if (($itemcnt % 2) == 0) {
            $eof = true;
        }
    }

    $_csv_line = preg_replace("/(?: |[ ])?$/", $d, trim($_line));
    $_csv_pattern = "/(" . $e . "[^" . $e . "]*(?:" . $e . $e . "[^" . $e . "]*)*" . $e . "|[^" . $d . "]*)" . $d . "/";
    preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
    $_csv_data = $_csv_matches[1];

    for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
        $_csv_data[$_csv_i] = preg_replace("/^" . $e . "(.*)" . $e . "$/s", "\$1", $_csv_data[$_csv_i]);
        $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
    }

    return empty($_line) ? false : $_csv_data;
}

//使用方法如下：读取CSV内容并导入系统中
//最常用PHP 字符串函数操作 $result = explode(",",$row[$i]);//读取数据到数组中，以英文逗号为分格符
if($_FILES['file']['size']>0 && $_FILES['file']['name']!=""){
    $file_size_max    = 8072000; //8000k
    $store_dir        = "./upload/";
    $ext_arr          = array('csv','xls','xlsx','txt');
    $accept_overwrite = true;
    $date1            = date("Y-m-d-His");
    $file_type        = extend($_FILES['file']['name']);
    $newname          = $date1.".".$file_type;
    //判断格式
    if (in_array($file_type,$ext_arr) === false){
        echo "<script>alert('请上传符合要求的模板格式');history.back()</script>";
        exit;
    }

    //判断文件的大小
    if ($_FILES['file']['size'] > $file_size_max) {
        echo "<script>alert('对不起，你上传的文件大于8M');history.back()</script>";
        exit;
    }

    if (file_exists($store_dir.$_FILES['file']['name'])&&!$accept_overwrite)
    {
        echo "<script>alert('文件已存在，不能新建');history.back()</script>";
        exit;
    }

    if (!move_uploaded_file($_FILES['file']['tmp_name'],$store_dir.$newname)) {
        echo "<script>alert('复制文件失败');history.back()</script>";
        exit;
    }

    $filepath = $store_dir.$newname;
}
else{
    $filepath = "";
}

if($filepath == ""){
    echo "<script>alert('请先选择要上传的文件');history.back()</script>";
    exit;
}

$file_encoding = $_POST["file_encoding"];

if($file_type == "csv") {
    setlocale(LC_ALL, 'zh_CN.UTF-8');
    $file = fopen($filepath, "r");
    $k = 1;
    while (!feof($file) && $data = __fgetcsv($file)) {

        $result = array();

        if ($k > 1 && !empty($data)) {
            for ($i = 0; $i < 16; $i++) {
                array_push($result, $data[$i]);
            }
            if ($file_encoding == "gbk") {
                //...do something
                $result_1 = iconv("gbk", "utf-8" . "//IGNORE", $result[1]);
            } else {
                //...do something
                $result_1 = $result[1];
            }
        }
        $k++;
    }
    fclose($file);
}
?>